package dingtalk

import (
	"errors"
	"parking-lot-go-dingding/model"
	"time"

	"gorm.io/gorm"
)

type DingtalkNewsStruct struct {
	Id        int       `json:"id" gorm:"type:int(10) unsigned auto_increment; NOT NULL; primary_key"`
	ClassId   int       `json:"class_id" gorm:"type:int(10); NOT NULL; COMMENT:'分类ID'"`
	Title     string    `json:"title" gorm:"type:varchar(100); COMMENT:'标题'"`
	Introduce string    `json:"introduce" gorm:"type:text; COMMENT:'介绍'"`
	Content   string    `json:"content" gorm:"type:text; COMMENT:'内容'"`
	ImagePath string    `json:"image_path" gorm:"type:varchar(255);COMMENT:'图片'"`
	Sort      int       `json:"sort" gorm:"type:int(11);  COMMENT:'排序'"`
	Clicks    int       `json:"clicks" gorm:"type:int(10);  COMMENT:'浏览量'"`
	IsTop     int8      `json:"is_top" gorm:"type:tinyint(1);  COMMENT:'置顶'"`
	IsShow    int       `json:"is_show" gorm:"type:tinyint(1);  COMMENT:'显示/禁用'"`
	Keywords  string    `json:"keywords" gorm:"type:varchar(100);  COMMENT:'关键词'"`
	State     int       `json:"state" gorm:"type:tinyint(1); "`
	CreatedAt time.Time `json:"created_at" gorm:"type:datetime"`
	UpdatedAt time.Time `json:"updated_at" gorm:"type:datetime"`
}

func (c *DingtalkNewsStruct) TableName() string {
	return "dingtalk_news"
}

// 新闻列表
func (c *DingtalkNewsStruct) List(classId int, keyword string, page, limit int) ([]DingtalkNewsStruct, error) {

	//页码
	if page == 0 {
		page = 1
	}

	//条数
	if limit == 0 {
		limit = 10
	}

	offset := (page - 1) * limit

	var list []DingtalkNewsStruct

	//查询条件
	where := map[string]interface{}{}
	where["class_id"] = classId
	where["state"] = 1
	if keyword != "" {
		where["keyword lile ?"] = "%%" + keyword + "%%"
	}

	db := model.Db

	if err := db.
		Table(c.TableName()).
		Where(where).
		Order("is_top desc").
		Order("sort desc").
		Limit(limit).
		Offset(offset).
		Scan(&list).Error; err != nil {
		return nil, err
	}

	return list, nil
}

func (c *DingtalkNewsStruct) First(id int) (DingtalkNewsStruct, error) {
	db := model.Db

	var dingtalkNewsStruct DingtalkNewsStruct
	err := db.Table(c.TableName()).Where("id", id).First(&dingtalkNewsStruct).Error

	if errors.Is(err, gorm.ErrRecordNotFound) {
		return dingtalkNewsStruct, errors.New("查询失败")
	}

	//点击量增加
	db.Table(c.TableName()).Where("id", id).Updates(map[string]interface{}{
		"clicks": gorm.Expr("clicks + ?", 1),
	})

	return dingtalkNewsStruct, nil
}
